package com.LeeCode;

/**
 * 翻倍以链表形式表示的数字
 */

public class Code2816 {
    public static void main(String[] args) {
        int[] arr = {1, 8, 9};
        ListNode head = Utils.arrayToListNode(arr);
        Utils.printListNode(new Code2816().doubleIt(head));
    }

    public ListNode doubleIt(ListNode head) {
        head = reverse(head);
        int carry = 0;
        ListNode cur = head;
        while (cur != null) {
            int val = cur.val * 2 + carry;
            cur.val = val % 10;
            carry = val / 10;
            if (cur.next == null && carry > 0) {
                cur.next = new ListNode(carry);
                cur = cur.next;
            }
            cur = cur.next;
        }
        return reverse(head);
    }

    private ListNode reverse(ListNode head) {
        ListNode prev = null, cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }
}
